import { AlertManager } from "../alert/AlertManager";
import { Notifier } from "../framework/Notifier";
import GlobalData from "../GlobalData";
import { ListenID } from "../ListenID";
import CaptureUtils from "../utils/Capture";
import { Util } from "../utils/Util";
import DeviceManager from "./DeviceManager";

export default class DouyinManager {

    private static _instance: DouyinManager = null;
    public static get inst(): DouyinManager {
        return this._instance || (this._instance = new DouyinManager());
    }

    constructor() {
    }

    login(ret: ({ login, userInfo }) => void, err?: Function) {
        if (Util.isDouyinGame()) {
            tt.login({
                force: true,
                success(_res) {
                    console.log("登录成功");
                    // 调用 getUserInfo 前, 请确保登录成功

                    // 获取用户信息
                    tt.getUserInfo({
                        // withCredentials: true,
                        // withRealNameAuthenticationInfo: true,
                        success(res) {
                            console.log(`getUserInfo 调用成功`, res.userInfo);

                            ret && ret({
                                login: _res,
                                userInfo: res.userInfo || {}
                            })
                        },
                        fail(res) {
                            console.log(`getUserInfo 调用失败1111`, res.errMsg);
                            ret && ret({
                                login: _res,
                                userInfo: res.userInfo
                            })
                        },
                    });
                },
                fail(res) {
                    console.log(`login 调用失败`);
                },
            });
        }
    }

    goSidebar() {
        if(!Util.isDouyinGame()){
            return;
        }
        if (Util.isDouyinGame()) {
            tt.navigateToScene({
                scene: "sidebar",
                success: (res) => {
                    console.log("navigate to scene success");
                    // 跳转成功回调逻辑
                },
                fail: (res) => {
                    console.log("navigate to scene fail: ", res);
                    // 跳转失败回调逻辑
                },
            });

        }
    }

    private videoAd;
    private interstitialAd;
    private adInitVideoAd(){
        if(!Util.isDouyinGame()){
            return;
        }
        this.videoAd = null;
        this.videoAd = tt.createRewardedVideoAd({
                adUnitId: "19ofc7oiokbhh3a2h7",
                // multiton: true,
                // multitonRewardedMsg: "观看视频可领取奖励",
            });
         
            this.videoAd.onLoad(() => {
                console.log("广告加载完成");
            });
            this.videoAd.load();
    }
    private adInitInterstitialAd(){
        console.log("adInitInterstitialAd");
        // this.interstitialAd = null;
        if(this.interstitialAd){
            this.interstitialAd.destroy().then(()=>{
                console.log("插屏广告销毁成功");
                this.interstitialAd = tt.createInterstitialAd({
                    adUnitId: "cgh7c6mlo11ecia1a1",
                });
                this.interstitialAd.load();

            })
            return;
        }
        this.interstitialAd = tt.createInterstitialAd({
            adUnitId: "cgh7c6mlo11ecia1a1",
        });
        this.interstitialAd.onLoad(() => {
            console.log("插屏广告加载完成");
        });
        this.interstitialAd.load();

        this.interstitialAd.onError((err) => {
            console.log("插屏广告加载start失败",err);
            GlobalData.inst.isLoadAdFail = true;
        
        });
    }
    adinit() {
        if(!Util.isDouyinGame()){
            return;
        }
        this.adInitVideoAd();
        this.adInitInterstitialAd();
    }

    playReward(callback: Function) {
        console.log("playReward");
        if(!Util.isDouyinGame()){
            return;
        }

        this.videoAd
                .show()
                .then(() => {
                    console.log("广告显示成功");
                })
                .catch((err) => {

                    console.log("广告组件出现问题", err);
                    //因为广告被封，添加提示
                    AlertManager.showNormalTips("暂无无广告数据");
                    Notifier.send(ListenID.TipsLoading_Hide);

                    // 可以手动加载一次
                    this.videoAd.load().then(() => {
                        console.log("手动加载成功");
                        // 加载成功后需要再显示广告
                        this.videoAd.show();
                    });
                });

            let listener = (res) => {
                console.log("广告关闭", res);
                //不需要的时候
                this.videoAd.offClose(listener);
                if (res.isEnded) {
                    callback("ok");
                } else {
                    callback("err");
                }
                if (res.count) {
                    //在支持多例模式的版本上会返回该字段，并且是否返回该字段与multiton是否为true无关
                    //判断观看了几次广告
            }
        }

        this.videoAd.onClose(listener); //这里监听广告的close 事件
    }
    // 不提前加载播放激励广告
    playRewardNoLoad(callback: Function) {
        if (Util.isDouyinGame()) {
            this.playReward(callback);
        }
    }

    share(uid) {
        if (Util.isDouyinGame()) {
            tt.shareAppMessage({
                title: "快来游戏里找我玩吧",
                desc: "这小游戏还挺有意思，点击就能玩",
                imageUrl: "",
                query: "uid=" + uid,
                success() {
                    console.log("分享成功");
                },
                fail(e) {
                    console.log("分享失败");
                },
            });
        }
    }

    shareAndroid(shareNode: cc.Node, showLoader?: cc.Sprite) {
        let capture = CaptureUtils.capture(shareNode);
        if (cc.isValid(showLoader)) {
            showLoader.spriteFrame = capture[0];
        }

        if (!jsb || !DeviceManager.inst.isAndroid) return;

        let url = CaptureUtils.toImgUrl(capture[1]);
        console.log("存储的地址", url);
        setTimeout(() => {
            jsb.reflection.callStaticMethod("com/jingyingxiaobing/blueclient/AppActivity", "DYShareImage", "(Ljava/lang/String;)V", url);

        }, 1000);
    }

    shareUrlAndroid(url: string) {
        jsb.reflection.callStaticMethod("com/jingyingxiaobing/blueclient/AppActivity", "DYShareUrl", "(Ljava/lang/String;)V", url);
    }

    getLocation(successCallback: Function, failCallback?: Function) {
        if (Util.isDouyinGame()) {
            tt.getLocation({
                success(res) {
                    console.log(`经度${res.longitude}，维度${res.latitude}`);
                    successCallback && successCallback(res);
                },
                fail(res) {
                    console.log(`getLocation调用失败`);
                    failCallback && failCallback();
                },
            });

        }
    }
    playCreateInterstitialAd(){
        console.log("playCreateInterstitialAd"); 
        if(Util.isDouyinGame()){
            if(GlobalData.inst.isLoadAdFail)
            {
                return;
            }
            this.interstitialAd.show().
            then(() => {
                console.log("插屏广告展示成功");
                // this.interstitialAd.destroy();
                // this.adInitInterstitialAd();
            }).catch((err)=>{
                console.log("插屏广告展示失败",err);
                if (err.code === -10005) {
                    // 表明当前app版本不支持插屏广告，可以提醒用户升级app版本
                    return 
                }
                this.adInitInterstitialAd();
            });
            this.interstitialAd.onError((err) => {
                console.log("插屏广告加载失败",err);
                this.adInitInterstitialAd();
            });
            this.interstitialAd.onClose((res)=>{
                console.log("插屏广告关闭",res);
                // this.interstitialAd.destroy();
                this.adInitInterstitialAd();
            })
        }
    }

}